package com.cbs.android.module.user.user.module;

import com.cbs.android.component.applicationutils.Global;
import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.Response;
import com.cbs.android.component.network.ResponseHandler;
import com.cbs.android.component.network.decoder.GsonDecoder;
import com.cbs.android.module.user.network.CBSUserRequest;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.google.gson.Gson;

import java.net.HttpURLConnection;

/**
 * Created by broche on 11/3/15.
 */
public class UserModuleGetInformation {
    private static final String UrlTpl = "%s/user/api/v1/users/{uid}/informations";
    private ModuleHandler<User> moduleHandler;

    public UserModuleGetInformation(ModuleHandler<User> moduleHandler) {
        this.moduleHandler = moduleHandler;
    }

    public void start() {
        if (UserModule.getUser() == null) {
            if (moduleHandler != null) {
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setErrorNo(99999);
                errorResponse.setErrorMsg("请先登录您的账号");
                moduleHandler.onFailure(999, new Gson().toJson(errorResponse));
            }
            return;
        }
        Request request = new CBSUserRequest(String.format(UrlTpl, Global.getServerHost()))
                .setDecoder(new GsonDecoder(User.class))
                .setResponseHandler(new ResponseHandler() {
                    @Override
                    public void onResponse(Response response) {
                        if (response.getCode() == HttpURLConnection.HTTP_OK) { // success
                            User user = ((User) response.getResult());
                            UserModule.setUser(user);
                            if (moduleHandler != null) {
                                moduleHandler.onSuccess(user);
                            }
                        } else { // unknown error
                            if (moduleHandler != null) {
                                moduleHandler.onFailure(response.getCode(), response.getResult().toString());
                            }
                        }
                    }

                    @Override
                    public void onException(Request request, Exception e) {
                        if (moduleHandler != null) {
                            moduleHandler.onException(e);
                        }
                    }
                });
        UserModule.getHttpClient().send(request);
    }
}
